package uilt;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.management.RuntimeErrorException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBUtil {
	private DBUtil() {

	}

	static Properties p = new Properties();
	static {
		try {
			InputStream is = DBUtil.class.getClassLoader().getResourceAsStream(
					"jdbc.properties");
			p.load(is);
			Class.forName(p.getProperty("driver"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// public static DataSource ds = getDs();
	//
	// public static Connection getConnection() {
	// Connection con = null;
	// try {
	// con = ds.getConnection();
	// System.out.println("::::::" + con.hashCode());
	// return con;
	// } catch (Exception e) {
	// e.printStackTrace();
	// throw new RuntimeException(e);
	// }
	// // return con;
	// }
	//
	// private static DataSource getDs() {
	// try {
	// Context ic = new InitialContext();
	// DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/xinwen");
	// return ds;
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return null;
	//
	// }

	public static Connection getConn() throws SQLException {
		String url = p.getProperty("url");
		Connection conn = DriverManager.getConnection(url,
				p.getProperty("useName"), p.getProperty("passWord"));
		return conn;
	}

	public static void close(Connection conn, Statement st, ResultSet rs) {
		close(rs);
		close(st);
		close(conn);
	}

	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void close(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
